<?php

namespace diszz\phpyac;

use Yii;
use yii\di\Instance;

class Cache extends \yii\caching\Cache
{
    /**
     * @var Connection|string|array the yac [[Connection]] object or the application component ID of the yac [[Connection]].
     * This can also be an array that is used to create a yac [[Connection]] instance in case you do not want do configure
     * yac connection as an application component.
     * After the Cache object is created, if you want to change this property, you should only assign it
     * with a yac [[Connection]] object.
     */
    public $yac = 'yac';

    /**
     * Initializes the yac Cache component.
     * This method will initialize the [[yac]] property to make sure it refers to a valid yac connection.
     * @throws \yii\base\InvalidConfigException if [[yac]] is invalid.
     */
    public function init()
    {
        \Yii::trace("cache init ", __CLASS__);
        
        parent::init();
        $this->yac = Instance::ensure($this->yac, Connection::className());
        $this->yac->open();
        
        \Yii::trace("cache init end ", __CLASS__);
    }

    /**
     * @inheritdoc
     */
    public function exists($key)
    {
        $key = $this->buildKey($key);
        return (bool)$this->yac->exists($key);
    }

    /**
     * @inheritdoc
     */
    protected function getValue($key)
    {
        return $this->yac->get($key);
    }

    /**
     * @inheritdoc
     */
    protected function getValues($keys)
    {
        return $this->yac->mget($keys);
    }

    /**
     * @inheritdoc
     */
    protected function setValue($key, $value, $expire)
    {
        return (bool)$this->yac->set($key, $value, $expire);
    }

    /**
     * @inheritdoc
     */
    protected function setValues($data, $expire)
    {
        return $this->yac->mset($data, $expire);
    }


    /**
     * @inheritdoc
     */
    protected function addValue($key, $value, $expire)
    {
        return $this->yac->add($key, $value, $expire);
    }

    /**
     * @inheritdoc
     */
    protected function deleteValue($key)
    {
        return (bool)$this->yac->del($key);
    }

    /**
     * @inheritdoc
     */
    protected function flushValues()
    {
        return $this->yac->flushdb();
    }
    
    public function getOrSet($key, $callable, $expire = 1800, $resetCache = false, $dependency = null)
    {
        $key = $this->buildKey($key);
        return $this->yac->getOrSet($key, $callable, $expire, $resetCache);
    }
}
